﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Golos.Polls.PollCache;
using Golos.Web.Utils;

namespace Golos.Web.handlers
{
    public class SearchHandler : HandlerBase
    {
        public SearchHandler(HttpContext httpContext)
            : base(httpContext)
        {
        }
        public override void Handle()
        {
            try
            {
                Token token = TokenUtils.FromCookies(_httpContext.Request.Cookies);

                string key = GetQueryParam("key");

                List<Guid> qIDs = PollsClient.SearchPoll(key);

                string json = "{";

                if (token != null)
                {
                    foreach (Guid questionId in qIDs)
                    {
                        UserAnswerInfo userAnswerInfo = PollsClient.GetUserAnswerInfo(questionId, token.User);

                        if (userAnswerInfo != null)
                        {
                            json += PollsHelper.GetVotedPollInfo(token.User, questionId);
                        }
                        else
                        {
                            json += PollsHelper.GetPollInfo(questionId);
                        }
                    }
                }
                else
                {
                    //Рисуем для анонимов
                    foreach (Guid questionId in qIDs)
                    {
                        json += PollsHelper.GetPollInfo(questionId);
                    }
                }
                json = json.TrimEnd(new char[] { ',', ' ' }) + "}";

                _httpContext.Response.Write(json);
            }
            catch (Exception e)
            {
                LogClass.WriteErrorEntry(e.ToString());
            }
        }
    }
}